package cn.achao.csr.base.config;

import cn.achao.csr.base.factory.MyThreadFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 统一线程池配置
 * @Author: achao
 **/
@Component
@EnableAsync
@Configuration
public class ThreadPoolConfig implements AsyncConfigurer {

   @Resource
   private ThreadConfigProperties threadConfig;


    @Override
    public Executor getAsyncExecutor() {
        return appChatExecutor();
    }

    /**
     * 应用线程池
     * @return
     */
    @Bean
    @Primary
    public ThreadPoolTaskExecutor appChatExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(threadConfig.getCorePoolSize());
        executor.setMaxPoolSize(threadConfig.getMaxPoolSize());
        executor.setQueueCapacity(threadConfig.getQueueCapacity());
        executor.setKeepAliveSeconds(threadConfig.getKeepAliveSeconds());
        executor.setThreadNamePrefix(threadConfig.getThreadName() + "-exec");
        //满了调用线程执行，认为重要任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setThreadFactory(new MyThreadFactory(executor));
        executor.initialize();
        return executor;
    }

}
